<script setup lang="ts">
import { ref, watch, computed } from 'vue'

const props = defineProps({
  condition: {
    type: Object,
    default: null,
    required: false
  },
  index: {
    type: Number,
    required: true
  },
  showNextStep: {
    type: Boolean,
    default: false
  },
  additionalConditionTypes: {
    type: Array<{ label: string, value: string }>,
    default: () => []
  }
})

const emit = defineEmits(['remove', 'capture', 'update:condition'])

// 添加模态弹窗相关的引用
const showModal = ref(false)
const modalImage = ref('')

// 添加缩放相关的引用
const scale = ref(1)
const translateX = ref(0)
const translateY = ref(0)
const isDragging = ref(false)
const dragStartX = ref(0)
const dragStartY = ref(0)
const startTranslateX = ref(0)
const startTranslateY = ref(0)

// 条件类型选项
// 文本类型： text_exists, text_exists_exact, text_not_exists
const conditionTypes = computed(() => {
  return [
    { label: '存在图片', value: 'image_exists' },
    { label: '存在文本', value: 'text_exists' },
    { label: '存在文本（精确匹配）', value: 'text_exists_exact' },
    { label: '不存在图片', value: 'image_not_exists' },
    { label: '不存在文本', value: 'text_not_exists' },
    ...props.additionalConditionTypes
  ]
})

// 条件项类型选项
const conditionItemTypes = [
  { label: '无条件', value: 'none' },
  { label: '简单条件', value: 'simple' },
  { label: '复合条件', value: 'composite' }
]

// 当前条件项类型（只读，根据传入的condition计算得出）
const currentConditionItemType = computed(() => {
  if (props.condition === null || (props.condition && props.condition.conditionType === 'none')) {
    return 'none'
  } else if (props.condition && typeof props.condition === 'object' && 'conditions' in props.condition) {
    return 'composite'
  } else if (props.condition && typeof props.condition === 'object') {
    return 'simple'
  }
  return 'none'
})

// 预览图片 URL（Base64 或 file://）
const previewImage = ref<string | null>(null)

// 监听 condition.value 变化，更新预览
watch(
  () => props.condition && typeof props.condition === 'object' && 'value' in props.condition ? props.condition.value : null,
  (newValue) => {
    if (newValue && typeof newValue === 'string') {
      if (newValue.startsWith('data:image')) {
        previewImage.value = newValue
      } else if (newValue.startsWith('file://')) {
        previewImage.value = newValue
      } else {
        previewImage.value = 'data:image/png;base64,' + newValue
      }
    } else {
      previewImage.value = null
    }
  },
  { immediate: true }
)

// 清除预览
const clearPreview = () => {
  previewImage.value = null
  if (props.condition && typeof props.condition === 'object' && 'value' in props.condition) {
    const updatedCondition = { ...props.condition, value: '' }
    emit('update:condition', updatedCondition)
  }
}

// 添加子条件（用于复合条件）
const addSubCondition = () => {
  if (props.condition && typeof props.condition === 'object' && 'conditions' in props.condition) {
    const updatedCondition = {
      ...props.condition,
      conditions: [
        ...props.condition.conditions,
        {
          conditionType: 'image_exists',
          value: ''
        }
      ]
    }
    emit('update:condition', updatedCondition)
  }
}

// 删除子条件（用于复合条件）
const removeSubCondition = (subIndex: number) => {
  if (props.condition && typeof props.condition === 'object' && 'conditions' in props.condition) {
    const newConditions = [...props.condition.conditions]
    newConditions.splice(subIndex, 1)

    const updatedCondition = {
      ...props.condition,
      conditions: newConditions
    }
    emit('update:condition', updatedCondition)
  }
}

// 更新子条件（用于复合条件）
const updateSubCondition = (subIndex: number, newSubCondition: any) => {
  if (props.condition && typeof props.condition === 'object' && 'conditions' in props.condition) {
    const newConditions = [...props.condition.conditions]
    newConditions.splice(subIndex, 1, newSubCondition)

    const updatedCondition = {
      ...props.condition,
      conditions: newConditions
    }
    emit('update:condition', updatedCondition)
  }
}

// 更新条件项类型（通知父组件进行数据修改）
const updateConditionItemType = (type: string) => {
  if (type === 'none') {
    emit('update:condition', {
      conditionType: 'none',
      value: ''
    })
  } else if (type === 'simple') {
    emit('update:condition', {
      conditionType: 'image_exists',
      value: ''
    })
  } else if (type === 'composite') {
    emit('update:condition', {
      conditions: [],
      operator: 'and'
    })
  }
}
// 添加 OCR 结果相关的引用
const ocrResults = ref<Array<[string, [number, number, number, number], number]>>([])

const TestCondition = async () => {
  // @ts-ignore
  const res = await window.pywebview.api.TestCondition(props.condition)
  if (res && res.suc) {
    // 显示模态弹窗，展示截图区域
    modalImage.value = res.marked_image || res.image
    showModal.value = true
    ocrResults.value = res.text || []
    // 重置缩放和位置
    scale.value = 1
    translateX.value = 0
    translateY.value = 0
    testConditionRes.value = res.res
    console.log('截图区域获取成功:', res)
  } else {
    // 处理错误情况
    testConditionRes.value = false
    console.error('截图区域获取失败:', res)
  }
}
const testConditionRes = ref(false)

// 关闭模态弹窗
const closeModal = () => {
  showModal.value = false
  modalImage.value = ''
}

// 处理鼠标滚轮缩放
const handleWheel = (e: WheelEvent) => {
  e.preventDefault()
  const delta = e.deltaY > 0 ? 0.9 : 1.1
  scale.value = Math.max(0.1, Math.min(5, scale.value * delta))
}

// 开始拖拽
const startDrag = (e: MouseEvent) => {
  isDragging.value = true
  dragStartX.value = e.clientX
  dragStartY.value = e.clientY
  startTranslateX.value = translateX.value
  startTranslateY.value = translateY.value
  ;(e.target as HTMLElement).style.cursor = 'grabbing'
}

// 拖拽中
const onDrag = (e: MouseEvent) => {
  if (!isDragging.value) return
  translateX.value = startTranslateX.value + (e.clientX - dragStartX.value)
  translateY.value = startTranslateY.value + (e.clientY - dragStartY.value)
}

// 结束拖拽
const endDrag = (e: MouseEvent) => {
  isDragging.value = false
  ;(e.target as HTMLElement).style.cursor = 'grab'
}

// 重置视图
const resetView = () => {
  scale.value = 1
  translateX.value = 0
  translateY.value = 0
}
</script>

<template>
  <div class="flex flex-col gap-2 mb-2 p-2 border border-gray-200 rounded hover:border-red-400">
    <!-- 模态弹窗 -->
    <div v-if="showModal" class="fixed inset-0 bg-black bg-opacity-90 z-50 flex flex-col">
      <div class="flex-1 overflow-hidden relative flex">
        <div
          class="flex-1 overflow-hidden relative"
          @mousemove="onDrag"
          @mouseup="endDrag"
          @mouseleave="endDrag"
          @wheel="handleWheel"
        >
          <div
            class="absolute inset-0 flex items-center justify-center"
            :style="{
              cursor: isDragging ? 'grabbing' : 'grab',
              transform: `translate(${translateX}px, ${translateY}px) scale(${scale})`,
              transformOrigin: 'center center'
            }"
            @mousedown="startDrag"
          >
            <img
              :src="modalImage"
              alt="截图区域预览"
              class="max-w-none"
            />
          </div>
        </div>

        <!-- OCR 文本结果展示区域 -->
        <div class="bg-gray-900 text-white p-1 overflow-y-auto pt-6" style="width: 300px;">
          <h3 class="text-lg font-bold mb-2">条件是否满足：{{ testConditionRes ? '是' : '否' }}</h3>
          <div class="space-y-2" v-if="['text_exists', 'text_exists_exact', 'text_not_exists'].includes(condition.conditionType)">
            <div
              v-for="(item, index) in ocrResults"
              :key="index"
              class="border border-green-500 p-2 relative"
            >
              <div class="text-sm font-semibold text-green-400">{{ item[0] }}</div>
              <div class="text-xs text-gray-400 mt-1">
                位置: ({{ item[1][0] }}, {{ item[1][1] }}, {{ item[1][2] }}, {{ item[1][3] }})
              </div>
              <div class="text-xs text-gray-400">
                置信度: {{ (item[2] * 100).toFixed(2) }}%
              </div>
            </div>
            <div v-if="ocrResults.length === 0" class="text-gray-500">
              未识别到文本或无OCR结果
            </div>
          </div>
        </div>

      </div>
      <div class="flex justify-between items-center bg-gray-800 text-white">
        <div class="p-2 bg-gray-800 text-white text-sm">
          缩放: {{ Math.round(scale * 100) }}% | 拖拽移动图像 | 滚轮缩放
        </div>
        <div class="flex space-x-2 items-center">
          <button @click="resetView" class="px-3 py-1 bg-gray-600 rounded hover:bg-gray-500">
            重置视图
          </button>
          <button @click="closeModal" class="px-3 py-1 bg-red-600 rounded hover:bg-red-500">
            关闭
          </button>
        </div>
      </div>
    </div>

    <!-- 条件项类型选择 -->
    <div class="flex flex-nowrap flex-row mb-2 justify-between w-full">
      <div class="flex flex-col gap-2 flex-1">
        <div id="条件类型选择" class="flex items-center flex-1">
          <div class="flex items-center p-0 m-0 border-gray-300" style="width:230px">
            <label class="mr-2 text-sm font-medium">条件类型:</label>
            <select :value="currentConditionItemType"
                    @change="e => updateConditionItemType((e.target as HTMLSelectElement).value)"
                    class="p-1 border border-gray-300 rounded flex-1">
              <option v-for="type in conditionItemTypes" :key="type.value" :value="type.value">
                {{ type.label }}
              </option>
            </select>
          </div>
          <!-- 区域限定输入框 -->
          <div class="flex flex-1 gap1 items-center" v-if="currentConditionItemType !== 'none'">
            <label class="text-right mr-2 text-sm font-medium whitespace-nowrap w-20">限定区域：</label>
            <input :value="condition.region || ''"
                   @input="e => emit('update:condition', { ...condition, region: (e.target as HTMLInputElement).value || undefined })"
                   type="text" class="flex-1 p-1 border border-gray-300 rounded text-sm"
                   placeholder="如: x1:10,y1:10,x2:400,y2:300 或 0.33w<x<0.66w" />
            <button
              @click="TestCondition" class="ml-2 px-2 py-1 bg-blue-500 text-white rounded text-xs">
              预览判定结果
            </button>
          </div>
        </div>

        <div id="条件详情">
          <div v-if="currentConditionItemType === 'none'" class="flex items-center">
            <span class="p-1 " style="width: 230px">任意条件始终满足</span>
            <div v-if="showNextStep" class="pl-3 flex-1 flex items-center">
              <!-- 下一步名称输入（仅在条件跳转中显示） -->
              <input :value="condition.nextStep"
                     @input="e => emit('update:condition', { ...condition, nextStep: (e.target as HTMLInputElement).value })"
                     type="text" class="p-1 border border-gray-300 rounded mr-2 flex-1" placeholder="下一步名称" />
              <button @click="emit('remove', index)"
                      class="px-2 py-1 bg-red-500 text-white rounded text-sm ml-2 items-center">
                删除
              </button>
            </div>

          </div>
          <!-- 简单条件 (TaskCondition) -->
          <div v-else-if="currentConditionItemType === 'simple' && condition" class="flex items-center">
            <!-- 条件类型选择 -->
            <select :value="condition.conditionType"
                    @change="e => emit('update:condition', { ...condition, conditionType: (e.target as HTMLSelectElement).value })"
                    class="p-1 border border-gray-300 rounded mr-2 flex-none" style="width:230px">
              <option v-for="type in conditionTypes" :key="type.value" :value="type.value">
                {{ type.label }}
              </option>
            </select>

            <!-- 输入框 + 截图按钮 -->
            <div class="flex flex-col gap-1 flex-1">
              <div class="flex items-center">
                <input :value="condition.value"
                       @input="e => emit('update:condition', { ...condition, value: (e.target as HTMLInputElement).value })"
                       type="text" class="flex-1 p-1 border border-gray-300 rounded" placeholder="输入文本或图片代码" />

                <!-- 当条件是图片相关时显示截图按钮 -->
                <button v-if="['image_exists', 'image_not_exists'].includes(condition.conditionType)"
                        @click="emit('capture', index)" class="ml-2 px-2 py-1 bg-blue-500 text-white rounded text-xs">
                  截取目标图片
                </button>
              </div>


            </div>

            <div v-if="showNextStep" class="px-3 flex-1 flex items-center">
              <!-- 下一步名称输入（仅在条件跳转中显示） -->
              <input :value="condition.nextStep"
                     @input="e => emit('update:condition', { ...condition, nextStep: (e.target as HTMLInputElement).value })"
                     type="text" class="p-1 border border-gray-300 rounded mr-2 flex-1" placeholder="下一步名称" />
              <button @click="emit('remove', index)"
                      class="px-2 py-1 bg-red-500 text-white rounded text-sm ml-2 items-center">
                删除
              </button>
            </div>
          </div>
          <!-- 复合条件 (CompositeCondition) -->
          <div v-else-if="currentConditionItemType === 'composite' && condition"
               class="border border-gray-300 rounded p-2 w-full">
            <div class="mb-2 flex items-center gap-2">
              <label class="mr-2">操作符:</label>
              <select :value="condition.operator"
                      @change="e => emit('update:condition', { ...condition, operator: (e.target as HTMLSelectElement).value })"
                      class="p-1 border border-gray-300 rounded">
                <option value="and">AND</option>
                <option value="or">OR</option>
              </select>
            </div>

            <!-- 子条件列表 -->
            <div id="子条件列表" class="mb-2">
              <div v-for="(subCondition, subIndex) in condition.conditions" :key="subIndex" class="mb-2">
                <div class="flex items-center">
                  <!-- flex-1让组件充满父容器 -->
                  <ConditionItem class="w-full" :condition="subCondition" :index="subIndex"
                                 @update:condition="(newCond) => updateSubCondition(subIndex, newCond)"
                                 @remove="() => removeSubCondition(subIndex)"
                                 @capture="(capIndex) => emit('capture', capIndex)" />
                </div>
              </div>
            </div>

            <!-- 添加子条件按钮 -->
            <div class="flex items-center border-t border-gray-200 pt-2 mt-2">
              <button @click="addSubCondition" class="px-2 py-1 bg-blue-500 text-white rounded text-sm">
                添加子条件
              </button>

              <div v-if="showNextStep" class="pl-3 flex-1 flex items-center">
                <!-- 下一步名称输入（仅在条件跳转中显示） -->
                <input :value="condition.nextStep"
                       @input="e => emit('update:condition', { ...condition, nextStep: (e.target as HTMLInputElement).value })"
                       type="text" class="p-1 border border-gray-300 rounded mr-2 flex-1" placeholder="下一步名称" />
                <button @click="emit('remove', index)"
                        class="px-2 py-1 bg-red-500 text-white rounded text-sm ml-2 items-center">
                  删除复合条件
                </button>
              </div>
            </div>


          </div>

        </div>

      </div>

      <div>
        <div id="预览截图区域"
             v-if="condition && ['image_exists', 'image_not_exists'].includes(condition.conditionType)"
             class="w-48 h-18 pl-2">
          <!-- 图片预览区域 -->
          <div v-if="previewImage" class="relative">
            <img :src="previewImage" alt="预览"
                 class="w-48 h-18 object-cover border border-gray-300 rounded cursor-pointer" @click="clearPreview" />
            <button @click="clearPreview"
                    class="absolute -top-1 -right-1 w-5 h-5 bg-red-500 text-white rounded-full text-xs flex items-start">
              ×
            </button>
          </div>
          <!-- 无预览图时显示"缩略图" -->
          <div v-else class="flex items-center justify-center w-full h-full text-gray-500 text-sm">
            缩略图
          </div>
        </div>
      </div>

    </div>


  </div>
</template>
